package com.cx.thread;

import lombok.SneakyThrows;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 2生产者
 * 1消费者
 *
 * @Author:cxy
 * @Date:2022/3/12 11:26
 */
public class CarProCunTest {

    public static void main(String[] args) {

        final Car car = new Car();

        final Thread thread1 = new Thread(new Consumer(car));
        final Thread thread2 = new Thread(new Producer(car));

        car.t1 = thread1;
        car.t2 = thread2;
        thread1.start();
        thread2.start();


    }



    // 缓冲区
    static class Car{

        private Queue<Integer> list = new ArrayBlockingQueue<>(1) ;

        Thread t1;
        Thread t2;


        public synchronized void put(int v) throws InterruptedException {
            while (list.size() != 0){
//                wait();
                LockSupport.unpark(t1);
                LockSupport.park();
            }


            list.add(v);
            System.out.println(Thread.currentThread().getName() +" put");
//            notify();
        }

        public synchronized int get() throws InterruptedException {
            if(list.size() == 0){
                LockSupport.unpark(t2);
                LockSupport.park();
            }
            System.out.println(Thread.currentThread().getName() +" get");
//            notify();
            return list.poll();
        }

    }


    // 生产者
    static class Producer implements Runnable{
        Car car;
        public Producer(Car car) {
            this.car = car;
        }

        @SneakyThrows
        @Override
        public void run() {
            while (!Thread.interrupted()){
                car.put(1);
                TimeUnit.SECONDS.sleep(1);
//                System.out.println(Thread.currentThread().getName() +" Producer.put1");
            }

        }
    }


    // 消费者
    static class Consumer implements Runnable{
        Car car;
        public Consumer(Car car) {
            this.car = car;
        }

        @SneakyThrows
        @Override
        public void run() {
            while (!Thread.interrupted()){
                car.get();
                TimeUnit.SECONDS.sleep(1);
//                System.out.println(Thread.currentThread().getName() +" Consumer.get1");
            }

        }
    }



}
